package com.ali.order.controller;

import com.ali.order.converter.OrderForm2OrderDTOConverter;
import com.ali.order.dto.OrderDTO;
import com.ali.order.enums.ResultEnum;
import com.ali.order.exception.OrderException;
import com.ali.order.form.OrderForm;
import com.ali.order.service.OrderService;
import com.ali.order.utils.ResultViewModelUtil;
import com.ali.order.viewmodel.ResultViewModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName OrderController
 * @Description TODO
 * @Author Alistair.Chow
 * @date 2018/12/21 12:16
 * @Version 1.0
 */
@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    OrderService orderService;
    /**
    * @Author Alistair.Chow
    * @Description 创建订单
    * @Date 12:16 2018/12/21
    * @Param []
    * @return void
    **/
    @PostMapping("/create")
    public ResultViewModel<Map<String, String>> create(@Valid OrderForm orderForm,
                       BindingResult bindingResult){
        // 参数校验
        if(bindingResult.hasErrors()){
            throw new OrderException(ResultEnum.PARAM_CODE.getCode(),
                    bindingResult.getFieldError().getDefaultMessage());
        }
        //orderForm -> OrderDTO
        OrderDTO orderDTO = OrderForm2OrderDTOConverter.convert(orderForm);
        if(CollectionUtils.isEmpty(orderDTO.getOrderDetailList())){
            throw new OrderException(ResultEnum.CART_EMPTY);
        }

        OrderDTO result = orderService.create(orderDTO);

        Map<String ,String> map = new HashMap<>(16);
        map.put("orderId", result.getId());
        return ResultViewModelUtil.success(map);
    }
}
